package priv.pfz.sbv;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.text.MessageFormat;
import java.util.Map;

/**
 * @author yyjxp
 * 2024/2/16 2:47
 */
public class Utils {
    public static String readResource(String filename) {
        try (InputStream is = ClassLoader.getSystemResourceAsStream(filename)) {
            return IOUtils.toString(is, StandardCharsets.UTF_8);
        } catch (IOException e) {
            throw new RuntimeException("读取资源文件异常:" + filename, e);
        }
    }

    public static void writeFile(String filename, String content) {
        try (OutputStream os = Files.newOutputStream(Paths.get(filename))) {
            IOUtils.write(content, os, StandardCharsets.UTF_8);
        } catch (IOException e) {
            throw new RuntimeException("写java源文件异常:" + filename, e);
        }
    }

    public static void writeFile(String templateName, Map<String, String> params, String filename) {
        try {
            Configuration configuration = new Configuration(Configuration.getVersion());
            configuration.setClassForTemplateLoading(Utils.class, "/");
            configuration.setDefaultEncoding("utf-8");
            Template template = configuration.getTemplate(templateName);
            try (Writer out = new FileWriter(filename)) {
                template.process(params, out);
            }
        } catch (IOException | TemplateException e) {
            throw new RuntimeException(e);
        }
    }

    public static String getFilename(String path, String filename) {
        if (path.endsWith("/") || path.endsWith("\\")) {
            return path + filename;
        } else {
            return path + "/" + filename;
        }
    }

    public static boolean isSpringInnerBean(String beanName) {
        return beanName.startsWith("org.springframework.context.");
    }

    public static void checkNotBlank(String param, String pattern, Object... arguments) {
        if (StringUtils.isBlank(param)) {
            throw new RuntimeException(MessageFormat.format(pattern, arguments));
        }
    }
}
